#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time      :2021/7/16 14:20
# @Author    :cjw
from fastapi import Depends, HTTPException, Security, status
from fastapi.security import OAuth2PasswordBearer
from jose import jwt, JWTError
from sqlalchemy.orm import Session

from app import crud
from app.api.utils.db import get_db
from app.core.config import settings
from app.models.user import User
from app.schemas.token import TokenPayload

reusable_oauth2 = OAuth2PasswordBearer(tokenUrl=f'{settings.API_V1_STR}/login/access-token')


def get_current_user(db: Session = Depends(get_db), token: str = Security(reusable_oauth2)) -> User:
	"""
	获取当前用户
	:param db: 数据库连接
	:param token: 令牌
	:return:
	"""
	try:
		payload = jwt.decode(token, settings.SECRET_KEY, algorithms=settings.ALGORITHM)
		token_data = TokenPayload(**payload)
	except JWTError:
		raise HTTPException(
			status_code=status.HTTP_403_FORBIDDEN,
			detail='无效的凭据！'
		)
	user = crud.user.get(db, token_data.user_id)
	if not user:
		HTTPException(
			status_code=status.HTTP_404_NOT_FOUND,
			detail='用户不存在！'
		)
	return user


def get_current_active_user(current_user: User = Security(get_current_user)) -> User:
	"""
	获取当前用户，是否是活跃用户
	:param current_user: 当前用户
	:return:
	"""
	if not crud.user.is_active(current_user):
		raise HTTPException(
			status_code=status.HTTP_400_BAD_REQUEST,
			detail='非活跃用户！'
		)
	return current_user


def get_current_active_superuser(active_user: User = Security(get_current_active_user)) -> User:
	"""
	获取当前活跃用户，是否是超级用户
	:param active_user: 活跃用户
	:return:
	"""
	if not crud.user.is_superuser(active_user):
		HTTPException(
			status_code=status.HTTP_400_BAD_REQUEST,
			detail='非超级用户，用户没有足够的权限！'
		)
	return active_user
